import mongoose from "mongoose";
import { Application } from "egg";
import AutoIncrementFactory from 'mongoose-sequence';
export interface userProps {
  username: string;
  password?: string;
  email?: string;
  nickname?: string;
  picure?: string;
  phoneNumber?: string;
  createdAt: Date;
  updatedAt: Date;
  type: 'email' | 'cellphone' | 'oauth';
  provider?: 'gitee',
  oauthId?: string;
}

const initUserModel = (app: Application) => {
  const autoIncreament = AutoIncrementFactory(app.mongoose);
  const userSchema = new mongoose.Schema<userProps>(
    {
      username: {
        type: String,
        unique: true,
        required: true
      },
      password: {
        type: String,
      },
      email: {
        type: String,
       
      },
      nickname: {
        type: String,
      },
      picure: {
        type: String,
      },
      phoneNumber: {
        type: String,
        unique: true
      },
      type: {
        type: String,
        enum: ['email', 'cellphone','oauth'],
        default: 'email'
      },
      provider: {
        type: String,
        enum: ['gitee'],
        default: 'gitee'
      },
      oauthId: {
        type: String,
      }
    },
    {
      // 添加createdAt 和 updatedAt 字段，并且自动更新
      timestamps: true,
      toJSON: {
        transform(_doc, ret) {
          delete ret.password;
          delete ret.__v;
        }
      }
    }
  );
  userSchema.plugin(autoIncreament, {inc_field: 'id'});
  return app.mongoose.model<userProps>("User", userSchema);
};

export default initUserModel;
